import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class HttpServer {
    public HttpServer(int port) {
        this.isRunning = false;
        this.port = port;
        this.router = new Router();
        this.threadPool = new ThreadPoolExecutor(
                20,
                50,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(128)
        );
    }

    // 服务注册接口
    public void get(String path, RequestHandler handler) {
        router.addRoute("GET", path, handler);
    }
    public void post(String path, RequestHandler handler) {
        router.addRoute("POST", path, handler);
    }
    public void put(String path, RequestHandler handler) {
        router.addRoute("PUT", path, handler);
    }
    public void delete(String path, RequestHandler handler) {
        router.addRoute("DELETE", path, handler);
    }

    public void start() {
        if (isRunning) {
            throw new IllegalStateException("服务器已经在运行中");
        }

        try {
            serverSocket = new ServerSocket(port);
            isRunning = true;

            System.out.println("服务器已启动！");
            // 服务器开始循环监听端口
            while (isRunning) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    ClientHandler clientHandler = new ClientHandler(clientSocket, router);
                    threadPool.execute(clientHandler);
                } catch (IOException e) {
                    if (isRunning) {
                        System.err.println("接受客户端连接时出错: " + e.getMessage());
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("启动服务器失败: " + e.getMessage(), e);
        }
    }

    public void stop() {
        isRunning = false;
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            System.err.println("关闭服务器套接字时出错: " + e.getMessage());
        }

        threadPool.shutdown();
    }

    private volatile boolean isRunning;          // 运行标志
    private final int port;                      // 端口号
    private final Router router;                 // 业务路由器
    private final ExecutorService threadPool;    // 线程池
    private ServerSocket serverSocket;           // 服务器套接字
}
